#include "g_types.h"
#include "binary_search_tree.h"

INT32 BTREE_Insert(BTREE_ROOT *tree, BTREE_NODE *node)
{
    if (tree == NULL) {
        return ERR;
    }

    BTREE_NODE *cur = tree->root;
    BTREE_NODE *p   = NULL;

    while (cur != NULL) {
        p = cur;
        if (node->val < cur->val) {
            cur = node->left;
        } else {
            cur = node->right;
        }
    }

    node->p = p;
    if (p == NULL) {
        tree->root = p;
    } else if (node->val < p->val) {
        p->left = node;
    } else {
        p->right = node;
    }

    return OK;
}